#include "level.h"
#include "globals.h"
#include "graphics.h"
#include <SDL.h>
#include <fstream>
#include <iostream>

Level::Level()
{

}

Level::Level(Graphics &G, int ID)
{
	Background = Sprite(G, "Content/Background.png", 0, 0, Globals::SCREEN_WIDTH, Globals::SCREEN_HEIGHT, 0, 0);
	std::ifstream Input;
	std::string Dir = "Content/Levels/";
	std::string Type = "Cell.lvl";
	std::string File = Dir;
	File += std::to_string(ID);
	File += Type;
	Input.open(File);
	//Now read all data and copy into a data store
	int CellData [Globals::SCREEN_HEIGHT / 16][Globals::SCREEN_WIDTH / 16];
	int CoinData [Globals::SCREEN_HEIGHT / 16][Globals::SCREEN_WIDTH / 16];
	while (Input.good())
	{
		for (int y = 0; y < Globals::SCREEN_HEIGHT / 16; y++)
		{
			for (int x = 0; x < Globals::SCREEN_WIDTH / 16; x++)
			{
				char* D[1];
				Input >> (char*)D;
				int I = atoi((char*)D);
				CellData[y][x] = I;
				SDL_Point P = SDL_Point();
				P.x = x;
				P.y = y;
				Cell C = Cell(G, I, P);
				Cells.push_back(C);
			}
		}
		Input.close();
	}
	Type = "Coin.lvl";
	File = Dir;
	File += std::to_string(ID);
	File += Type;
	Input.open(File);
	while (Input.good())
	{
		for (int y = 0; y < Globals::SCREEN_HEIGHT / 16; y++)
		{
			for (int x = 0; x < Globals::SCREEN_WIDTH / 16; x++)
			{
				char* D[1];
				Input >> (char*)D;
				int I = atoi((char*)D);
				if (I == 1)
				{
					CoinData[y][x] = I;
					SDL_Point P = SDL_Point();
					P.x = x;
					P.y = y;
					Coin C = Coin(G, P);
					Coins.push_back(C);
				}
			}
		}
		Input.close();
	}
}

void Level::Update(float ElapsedTime)
{
	for (int i = 0; i < Coins.size(); i++)
	{
		Coins[i].Update(ElapsedTime);
	}
}

void Level::Draw(Graphics &G)
{
	Background.Draw(G, SDL_RendererFlip::SDL_FLIP_NONE);
	for (int i = 0; i < Cells.size(); i++)
	{
		if (Cells[i].Type != 0)
			Cells[i].Draw(G);
	}
	for (int i = 0; i < Coins.size(); i++)
	{
		Coins[i].Draw(G);
	}
}